<template>
    <div class="roles">
              <!--头部面包屑导航-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <el-row>
                <el-col><el-button type="primary" class="addbtn" @click="addrole">添加角色</el-button></el-col>
            </el-row>
            <!--角色列表区-->
            <el-table border stripe :data="roleslist">
                <el-table-column type="expand" width="40">
                    <template slot-scope="scope">
                        <el-row :class="{topborder:i==0}" class="vcenter" v-for="(item1,i) in scope.row.children" :key="item1.id">
                            <!--渲染一级权限-->
                            <el-col :span="5">
                               <el-tag closable @close="removeright(scope.row,item1.id)">{{item1.authName}}</el-tag>
                               <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!--渲染二级和三级权限-->
                            <el-col :span="19">
                                <!--通过for循环渲染二级权限数据-->
                                <el-row class="vcenter" :class="[i2==0?'':'topborder']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag closable @close="removeright(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag @close="removeright(scope.row,item3.id)" closable v-for="(item3) in item2.children" :key="item3.id" type="warning">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                           
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column  label="操作" width="360">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="editrole(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleterole(scope.row)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showsetRole(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!--添加角色-->
        <el-dialog
            title="添加角色"
            :visible.sync="addroledialogVisible"
            width="30%"
            >
            <el-form :model="addroleruleForm" :rules="addrolerules" ref="addroleruleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addroleruleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addroleruleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addroledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addrolesure">确 定</el-button>
            </span>
        </el-dialog>
        <!--编辑角色-->
        <el-dialog
            title="编辑角色"
            :visible.sync="editroledialogVisible"
            width="30%"
            >
            <el-form :model="editroleruleForm" :rules="editrolerules" ref="editroleruleForm" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editroleruleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editroleruleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editroledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editrolesure">确 定</el-button>
            </span>
        </el-dialog>
        <!--分配权限-->
        <el-dialog
            title="分配权限"
            :visible.sync="setrightroledialogVisible"
            width="30%"
            @close="closerights"
            >
            <!--树形控件-->
           <el-tree ref="treeRef" :data="rightslist" :props="defaultProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setrightroledialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setrighttrolesure">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            roleslist:[],
            rightslist:[],//完整权限数据
            addroledialogVisible:false,
            editroledialogVisible:false,
            setrightroledialogVisible:false,
            addroleruleForm:{
                roleName:'',
                roleDesc:''
            },
            addrolerules: {
                 roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 4, max: 6, message: '长度在 4 到 6 个字符', trigger: 'blur' }
                ],roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3到 10 个字符', trigger: 'blur' }
                ],
            },
            editroleruleForm:{
                id:1,
                roleName:'',
                roleDesc:""
            },
            editrolerules: {
                 roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 4, max: 6, message: '长度在 4 到 6 个字符', trigger: 'blur' }
                ],roleDesc: [
                    { required: true, message: '请输入角色描述', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3到 10 个字符', trigger: 'blur' }
                ],
            },
            defaultProps: {
                children: 'children',
                label: 'authName'
            },
            defkeys:[],//默认选择的权限id数组
            roleid:"" //当前角色id
        }
    },
    created() {
        //获取角色列表数据
        this.getroleslist()
    },
    methods: {
        //获取角色列表数据
        async getroleslist(){
            const {data:res} = await this.$http.get('roles')
            if(res.meta.status!=200) return this.$message.error("获取角色列表数据失败")
            this.roleslist = res.data
            console.log(this.roleslist)
        },
        //添加角色
        addrole(){
            this.addroledialogVisible=true
        },
        //确定添加角色
        addrolesure(){
            //完成添加角色的预校验
            this.$refs.addroleruleForm.validate(async (valid)=>{
                if(!valid) return 
                // 发起请求添加角色
                const {data:res} = await this.$http.post('roles',this.addroleruleForm)
                if(res.meta.status!=201) return this.$message.error("添加角色数据失败")
                this.getroleslist()  
                this.addroledialogVisible = false
                return this.$message.success("添加角色成功")
            })
        },
        //删除角色
        async deleterole(role){
            //确定是否删除
            const deleterole =  await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            console.log(deleterole)
            if(deleterole!='confirm') return this.$message.info("您取消了本次删除操作")
            //发起请求确认删除
            const {data:res} = await this.$http.delete('roles/'+role.id)
            if(res.meta.status!=200) return this.$message.error("删除失败")
            this.getroleslist()
            return this.$message.success("删除成功")
        },
        //编辑角色
        editrole(role){
            this.editroleruleForm = role
            this.editroledialogVisible = true
        },
        //编辑弹框中确认按钮的处理函数
        editrolesure(){
            //完成编辑弹框中的表单数据预验证
            this.$refs.editroleruleForm.validate(async (valid)=>{
                if(!valid) return
                // 验证成功 发起网络请求完成数据的编辑
                const {data:res} = await this.$http.put('roles/'+this.editroleruleForm.id,this.editroleruleForm)
                if(res.meta.status!=200) return this.$message.error("编辑角色数据失败")
                this.getroleslist()
                this.editroledialogVisible =false
                return this.$message.success("编辑角色成功")
            })
        },
        //删除三级权限
        async removeright(role,rightid){
           const deleteroleright =  await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            if(deleteroleright!="confirm") return this.$message.info("您取消了该操作")
            //发起删除三级权限的请求
            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
            if(res.meta.status!=200) return this.$message.error("删除权限失败")
            role.children = res.data
            this.$message.success("删除权限成功")
        },
        //分配权限
        async showsetRole(row){
            //获取所以权限的数据
            this.roleid= row.id
            const {data:res} =await this.$http.get('rights/tree')
            if(res.meta.status!=200) return this.$message.error("获取权限数据失败")
            this.rightslist = res.data
            //获取三级节点的id
            this.getLeafkeys(row,this.defkeys)
            this.setrightroledialogVisible =true
            
        },
        //分配权限弹出框点击确定的处理函数
        async setrighttrolesure(){
            //得到选择权限id数组
            const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idstr = keys.join(',')
            const {data:res} = await this.$http.post('roles/'+this.roleid+'/rights',{rids:idstr})
            if(res.meta.status!=200) return this.$message.error("分配角色权限失败")
            this.getroleslist()
            this.setrightroledialogVisible= false
            return this.$message.success("分配角色权限成功")

        },
        //通过递归函数获取三级权限id
        getLeafkeys(node,arr){
            if(!node.children){
                //如果当前节点不包含children属性证明该节点是第三级权限
                return arr.push(node.id)
            }
            node.children.forEach(item=>{
                this.getLeafkeys(item,arr)
            })
        },
        //关闭分配权限对话框
        closerights(){
            this.defkeys=[]
        }
    },
}
</script>

<style scoped>
.addbtn{
    margin-bottom: 15px;
}
.el-tag{
    margin: 7px 4px 7px 40px; 
}
.el-row{
    border-bottom: 1px solid #eee;
}
.topborder{
    border-top: 1px solid #eee;
}
.vcenter{
    display: flex;
    align-items: center;
}
</style>